package com.onlinemusic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onlinemusic.common.R;
import com.onlinemusic.mapper.CartListMapper;
import com.onlinemusic.pojo.domain.CartList;
import com.onlinemusic.pojo.request.CartListRequest;
import com.onlinemusic.pojo.request.CartListRespo;
import com.onlinemusic.service.CartListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartListServiceImpl extends ServiceImpl<CartListMapper, CartList> implements CartListService {

    @Autowired
    private CartListMapper cartListMapper;

    /**
     * 选择歌曲加入购物车
     *
     * @param cartListRequest
     * @return R
     */
    @Override
    public R addCartList(CartListRequest cartListRequest) {
        //封装数据
        CartList cartList = new CartList();
        BeanUtils.copyProperties(cartListRequest, cartList);
        cartList.setCreateTime(new Date());
        int insert = 0;
        //重复则抛出异常
        try {
            insert = cartListMapper.insert(cartList);
        } catch (DataAccessException e) {
            e.printStackTrace();
            if (e.getMessage().contains("idx_cart_list_usersongid_unique")) {
                return R.warning("购物车中已存在相同歌曲");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("加入购物车时发生错误：" + e.getMessage());
        }

        if (insert > 0) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 删除购物车
     * @param userId
     * @param songIds
     * @return
     */
    @Override
    public R deleteCartList(Integer userId, List<Integer> songIds) {
        try {
            cartListMapper.delCartListBySongId(userId, songIds);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fatal("删除失败");
        }

        return R.success("删除成功");
    }

    /**
     * 返回某用户的购物车信息
     * @param userId
     * @return R
     */
    @Override
    public R allCartList(Integer userId) {
        if (userId == null) {
            return R.error("参数输入错误");
        }
        CartList cartList = new CartList();
        cartList.setUserId(userId);
        List<CartListRespo> cartListRespos = null;
        try {
            cartListRespos = cartListMapper.selectCartLists(cartList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fatal(e.getMessage());
        }
        return R.success(null, cartListRespos);
    }
}

